// 判断用户是登录
var username = getCookie('username')
if (!username) {
    alert('请重新登录')
    localStorage.setItem('url', location.href)
    location.href = 'login.html'
}

// 获取div
var div = document.querySelector('.cart')
var tbody = document.querySelector('.cart tbody')

// 获取购物车数据，渲染到页面中即可

sendAjax({
    url: 'http://localhost:8888/cart/list',
    data: {
        id: getCookie('userId')
    },
    headers: {
        authorization: localStorage.getItem('token')
    },
    success: res => {
        console.log(res);
        // 判断用户购物车获取都到的数据是否为空
        if (res.cart.length) {
            // 有数据 - 渲染
            var str = ''
            res.cart.forEach(v => {
                str += `
                <tr>
                <td data-id ="${v.goods_id}">
                    <input type="checkbox" name="selectOne" ${v.is_select?'checked':''}>
                </td>
                <td>
                    <img src="${v.img_small_logo}" alt="">
                </td>
                <td class="title" width="100">${v.title.slice(0,10)}</td>
                <td>${v.price}</td>
                <td>
                    <input type="button" value="-" class="reduce">
                    <input type="number" name="number"  value="${v.cart_number}"data-stock="${v.goods_number}">
                    <input type="button" value="+" class="add">
                </td>
                <td class="subtotal">${v.price * v.cart_number}</td>
                <td>删除</td>
            </tr>
                `
            })
            // 数据渲染到页面
            tbody.innerHTML = str
            // 数据渲染完成
            // 在购物车页面的功能
            /*
            1.全选
            2.单选
            3.数量加和减
            4.计算小计
            5.计算总价格总数量的功能
            6.删除单个商品
            7.删除选中商品的功能
            8.清空购物车的功能
            */
            //全选功能
            selectAll()
            //单选功能
            selectOne()
            // 数量加和减
            addAndReduce()
            // 小计功能
            subtotal()
            // // 总数量和总价格
            total()
            //删除单个商品的功能
            remove()
            // 删除选择商品的功能
            removeSelected()
            // //清空购物车
            clear()

        } else {
            // 购物车是空的，去挑选商品吧
            div.innerHTML = '购物车是空的，去挑选商品吧！<a href="list.html">商品页面</a>'
        }
    }
})
// 8.清空购物车的功能
function clear() {
    document.querySelector('.clear').onclick = function () {
        if (!confirm('是否确定要删除选中的商品')) return

        var tbody = document.querySelector('tbody')
        tbody.innerHTML = ''

        sendAjax({
            url: 'http://localhost:8888/cart/clear',
            headers: {
                authorization: localStorage.getItem('token')
            },
            data: {
                id: getCookie('userId'),
            },
            success: res => {
                console.log(res),
                    div.innerHTML = '购物车是空的，去挑选商品吧！<a href="list.html">商品页面</a>'
            }

        })
    }
}

// // 7.删除选中商品的功能
function removeSelected() {
    document.querySelector('.removeSelected').onclick = function () {
        if (!confirm('是否确定要删除选中的商品')) return
        // 从tbody中将没有选中的tr保留下来即可
        var trs = document.querySelectorAll('tbody>tr')
        // 将tbody内容清空
        var tbody = document.querySelector('tbody')
        tbody.innerHTML = ''
        // 遍历找出哪个是未选中
        for (var i = 0; i < trs.length; i++) {
            if (!trs[i].firstElementChild.firstElementChild.checked) {
                tbody.appendChild(trs[i])
            }
        }

        sendAjax({
            url: 'http://localhost:8888/cart/remove/select',
            headers: {
                authorization: localStorage.getItem('token')
            },
            data: {
                id: getCookie('userId')
            },
            success: res => {
                console.log(res)
                total()
                if (document.querySelector('tbody').children.length === 0) {
                    div.innerHTML = '购物车是空的，去挑选商品吧！<a href="list.html">商品页面</a>'
                }
            }
        })

    }
}
// // 6.删除单个商品的功能

function remove() {
    // 获取删除按钮
    var removeBtns = document.querySelectorAll('tbody td:last-child')
    // 循环绑定
    for (var i = 0; i < removeBtns.length; i++) {
        removeBtns[i].onclick = function () {
            // 询问客户是否确定要删除
            if (!confirm('是否确定要删除当前商品')) return

            this.parentElement.parentElement.removeChild(this.parentElement)

            // 发送AJax请求删除当前商品
            // 获取当前商品id
            var id = this.parentElement.firstElementChild.getAttribute('data-id')

            sendAjax({
                url: 'http://localhost:8888/cart/remove',
                headers: {
                    authorization: localStorage.getItem('token')
                },
                data: {
                    id: getCookie('userId'),
                    goodsId: id,
                },
                success: res => {
                    console.log(res)
                    total()
                    // 判断购物车数据是否存在

                    if (document.querySelector('tbody').children.length === 0) {
                        div.innerHTML = '购物车是空的，去挑选商品吧！<a href="list.html">商品页面</a>'
                    }
                }
            })
        }
    }
}

// 5.计算总数量和总价格
function total() {
    // 获取所有单选框，伪数组转数组。
    var selectOne = document.querySelectorAll('[name="selectOne"]')
    var arr = Array.prototype.slice.call(selectOne)
    var brr = arr.filter(item => item.checked)

    //格式化总价格.总数量
    var totalPrice = 0
    var totalNum = 0
    brr.forEach(item => {
        var sumPrice = +item.parentElement.parentElement.lastElementChild.previousElementSibling.innerText
        totalPrice += sumPrice

        var sumNum = +item.parentElement.parentElement.children[4].children[1].value
        totalNum += sumNum
    })
    document.querySelector('.totalPrice').innerText = totalPrice.toFixed(2)
    document.querySelector('.totalNum').innerText = totalNum
}

// 4.计算小计
function subtotal() {
    // 获取所有数量的文本框
    var numInput = document.querySelectorAll('[name="number"]')

    // 循环计算 商品数量*商品单价
    for (i = 0; i < numInput.length; i++) {
        var num = numInput[i].value
        var price = numInput[i].parentElement.previousElementSibling.innerText

        var sub = num * price
        numInput[i].parentElement.nextElementSibling.innerText = sub.toFixed(2)
    }

}

// 3.数量的加和减
function addAndReduce() {
    // 获取加按钮
    var addBtns = document.querySelectorAll('.add')
    for (var i = 0; i < addBtns.length; i++) {
        addBtns[i].onclick = function () {
            //获取this的上一个兄弟标签 
            var num = +this.previousElementSibling.value

            num++

            // 获取当前商品的库存
            var stock = +this.previousElementSibling.getAttribute('data-stock')
            if (num > stock) {
                num = stock
                return
            }

            // 将自增后的num值重新赋值给上一个兄弟标签
            this.previousElementSibling.value = num

            // 获取当前的商品id【this的父标签的父标签的第一个子标签】

            var id = this.parentElement.parentElement.firstElementChild.getAttribute('data-id')
            sendAjax({
                url: 'http://localhost:8888/cart/number',
                method: 'post',
                headers: {
                    authorization: localStorage.getItem('token')
                },
                data: {
                    id: getCookie('userId'),
                    goodsId: id,
                    number: num
                },
                success: res => {
                    console.log(res);
                    subtotal()
                    total()
                }
            })
        }
    }

    // 获取减按钮
    var reduceBtns = document.querySelectorAll('.reduce')
    for (var i = 0; i < reduceBtns.length; i++) {
        reduceBtns[i].onclick = function () {
            //获取this的下一个兄弟标签 
            var num = +this.nextElementSibling.value

            num--

            if (num < 1) {
                num = 1
                return
            }

            // 将自减后的num值重新赋值给上一个兄弟标签
            this.nextElementSibling.value = num

            // 获取当前的商品id【this的父标签的父标签的第一个子标签】

            var id = this.parentElement.parentElement.firstElementChild.getAttribute('data-id')
            sendAjax({
                url: 'http://localhost:8888/cart/number',
                method: 'post',
                headers: {
                    authorization: localStorage.getItem('token')
                },
                data: {
                    id: getCookie('userId'),
                    goodsId: id,
                    number: num
                },
                success: res => {
                    console.log(res);
                    subtotal()
                    total()
                }
            })
        }
    }

    // 手动修改文本框中的数量
    var numInput = document.querySelectorAll('[name="number"]')
    for (i = 0; i < numInput.length; i++) {
        numInput[i].oninput = function () {
            // 获取库存
            var stock = +this.getAttribute('data-stock')
            if (+this.value > stock) {
                this.value = stock
            }
            if (+this.value < 1) {
                this.value = 1
            }
        }
        numInput[i].onblur = function () {
            var num = +this.value
            var id = this.parentElement.parentElement.firstElementChild.getAttribute('data-id')
            sendAjax({
                url: 'http://localhost:8888/cart/number',
                method: 'post',
                headers: {
                    authorization: localStorage.getItem('token')
                },
                data: {
                    id: getCookie('userId'),
                    goodsId: id,
                    number: num
                },
                success: res => {
                    console.log(res);
                    subtotal()
                    total()
                }
            })
        }
    }
}

// 2.单选功能
function selectOne() {
    var selectAllBtn = document.querySelectorAll('[name="selectAll"]')
    var selectOneBtn = document.querySelectorAll('[name="selectOne"]')
    for (var i = 0; i < selectOneBtn.length; i++) {
        selectOneBtn[i].onclick = function () {
            var arr = Array.prototype.slice.call(selectOneBtn)

            var bool = arr.every(item => item.checked)
            for (var j = 0; j < selectAllBtn.length; j++) {
                selectAllBtn[j].checked = bool
            }
            // 发生ajax改变每个单选的选中状态的数据

            // 获取当前点击的这个单选所在商品的id - 在渲染页面的时候，给当前复选框的td上添加一个属性：data-id 对应的值就是当前商品的id
            var id = this.parentElement.getAttribute('data-id')
            sendAjax({
                url: 'http://localhost:8888/cart/select',
                method: 'post',
                headers: {
                    authorization: localStorage.getItem('token'),
                },
                data: {
                    id: getCookie('userId'),
                    userId: id
                },
                success: res => {
                    console.log(res)
                    total()
                }
            })

        }
    }
}

// 1.全选功能
function selectAll() {
    var selectAllBtn = document.querySelectorAll('[name="selectAll"]')
    var selectOneBtn = document.querySelectorAll('[name="selectOne"]')

    // 将伪数组转为数组
    var arr = Array.prototype.slice.call(selectOneBtn)

    // 对这个数组进行遍历判断布尔值
    var bool = arr.every(item => {
        return item.checked
    })
    for (var j = 0; j < selectAllBtn.length; j++) {
        selectAllBtn[j].checked = bool
    }
    for (var i = 0; i < selectAllBtn.length; i++) {
        selectAllBtn[i].onclick = function () {
            var checkedStatus = this.checked
            for (var j = 0; j < selectOneBtn.length; j++) {
                selectOneBtn[j].checked = checkedStatus
            }
            for (var j = 0; j < selectAllBtn.length; j++) {
                selectAllBtn[j].checked = checkedStatus
            }
            sendAjax({
                url: 'http://localhost:8888/cart/select/all',
                method: 'post',
                headers: {
                    authorization: localStorage.getItem('token')
                },
                data: {
                    id: getCookie('userId'),
                    type: Number(checkedStatus)
                },
                success: res => {
                    console.log(res);
                    total()
                }
            })
        }
    }
}